using System;
using System.Net;

#if WINDOWS_RT
using System.Net.Http;
using System.Threading.Tasks;
#endif

namespace AdRotator.Networking
{
    internal class Network
    {
        public static void GetStringFromURL(Uri uri, Action<string, Exception> callback)
        {
#if WINDOWS_RT
            var c = new HttpClient();


            Task.Run(async () =>
                    {
                        var result = await c.GetStringAsync(uri);

                        if (!string.IsNullOrEmpty(result))
                            callback(result, null);
                    });
#else
            var c = new WebClient();
            //  c.AllowReadStreamBuffering = false;
            c.DownloadStringCompleted += (sender, e) =>
            {
                if (e.Error == null)
                    callback(e.Result, null);
                else
                    callback(null, e.Error);
            };

            c.DownloadStringAsync(uri);
#endif

        }

        internal static void GetDeviceIP(Action<string, Exception> callback)
        {
            var uri = new Uri("http://compiledexperience.com/windows-phone-7/my-ip", UriKind.Absolute);

#if WINDOWS_RT
            var c = new HttpClient();

            Task.Run(async () =>
            {
                var result = await c.GetStringAsync(uri);

                if (string.IsNullOrEmpty(result))
                    return;

                var value = result.Split(new Char[] { '"' });
                callback(value[3], null);
            });
#else
            var webClient = new WebClient();
            
            webClient.DownloadStringCompleted += (sender, e) =>
                {
                    if (e.Error == null)
                    {
                        var value = ((string)e.Result).Split(new Char[] { '"' });
                        callback(value[3], null);
                    }
                    else
                        callback(null, e.Error);
                };

            webClient.DownloadStringAsync(uri);
#endif
        }

    }
}
